package es.abredatos.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.tidy.Tidy;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import es.abredatos.client.BooksLocatorService;
import es.abredatos.shared.Book;
import es.abredatos.shared.Library;

@SuppressWarnings("serial")
public class BooksLocatorServiceImpl extends RemoteServiceServlet implements BooksLocatorService {

	private List<Book> books;
	private List<Library> libraries;

	public BooksLocatorServiceImpl() {

		Book book1 = new Book();
		book1.setID(0);
		book1.setTitle("Libro uno");
		book1.setDescription("Descripcion del libro");

		Book book2 = new Book();
		book2.setID(1);
		book2.setTitle("Libro dos");
		book2.setDescription("Descripcion del libro");

		Book book3 = new Book();
		book3.setID(2);
		book3.setTitle("Libro tres");
		book3.setDescription("Descripcion del libro");

		Book book4 = new Book();
		book4.setID(3);
		book4.setTitle("Libro cuatro");
		book4.setDescription("Descripcion del libro");

		Book book5 = new Book();
		book5.setID(4);
		book5.setTitle("Libro cinco");
		book5.setDescription("Descripcion del libro");

		books = new ArrayList<Book>();
		books.add(book1);
		books.add(book2);
		books.add(book3);
		books.add(book4);
		books.add(book5);

		Library library1 = new Library();
		library1.setID(0);
		library1.setName("Biblioteca Municipal tijuana");
		library1.setAddress("Tijuana 20");
		library1.setCoordinates(28.059, -15.445);

		Library library2 = new Library();
		library2.setID(1);
		library2.setName("Biblioteca Salto del tigre");
		library2.setAddress("Salto del tigre s/n");
		library2.setCoordinates(28.070, -15.447);

		Library library3 = new Library();
		library3.setID(2);
		library3.setName("Biblioteca Pública Carioca");
		library3.setAddress("Camino largo 14");
		library3.setCoordinates(28.040, -15.430);

		libraries = new ArrayList<Library>();
		libraries.add(library1);
		libraries.add(library2);
		libraries.add(library3);

	}

	public List<Book> searchBook(String query, String type, boolean borrowed, double latitude, double longitude) throws IllegalArgumentException {

		System.out.println("searchBooks " + query);
		// ArrayList<Book> books = new ArrayList<Book>();

		// String target = "http://serdis.dis.ulpgc.es/~a013775/test.html";
		// String xpath =
		// ".//*[@id='abnoplist']/table/tbody/tr[3]/td/table[3]/tbody/tr[1]/td/table[3]/tbody/tr[*]/td[2]/table/tbody/tr/td[2]/a/text()";
		// ArrayList<String> result = xpathTest(target, xpath);
		// for (Iterator<String> iterator = result.iterator();
		// iterator.hasNext();) {
		// String title = (String) iterator.next();
		//
		// Book book = new Book();
		// book.setTitle(title);
		//
		// books.add(book);
		// }

		return books;
	}

	public List<Library> locateLibrary(Book book) throws IllegalArgumentException {

		System.out.println("locateLibrary" + book);

		return libraries;
	}

	public Book getBookDetails(String id) throws IllegalArgumentException {

		System.out.println("bookDetails " + id);

		return books.get(0);
	}

	private List<String> xpathTest(String target, String filter) {

		List<String> result = new ArrayList<String>();

		try {
			// URL url = new URL(target);
			// url.openConnection();
			// BufferedReader reader = new BufferedReader(new
			// InputStreamReader(url.openStream(), "iso-8859-1"));

			String html = urlPostTest(target);

			Tidy tidy = new Tidy();
			tidy.setMakeClean(true);
			Document doc = tidy.parseDOM(new StringReader(html), null);

			XPath xpath = XPathFactory.newInstance().newXPath();
			XPathExpression expression = xpath.compile(filter);
			NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);

			System.out.println(nodes.getLength());

			for (int i = 0; i < nodes.getLength(); i++) {
				String value = nodes.item(i).getNodeValue();

				System.out.println("........... " + value);

				result.add(value);
			}

		} catch (XPathException e) {
			e.printStackTrace();
		}

		return result;
	}

	public String urlPostTest(String target) {
		StringBuffer buffer = new StringBuffer();
		try {
			String stringToReverse = URLEncoder.encode("parameters", "UTF-8");
			URL url = new URL(target);
			URLConnection connection = url.openConnection();
			connection.setDoOutput(true);
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
			out.write("string=" + stringToReverse);
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String decodedString;
			while ((decodedString = in.readLine()) != null) {
				buffer.append(decodedString);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	private void datastoreTest() {
		TutorialUtils utils = new TutorialUtils();
		TutorialUtils.insert("Profesor pepe", "curso de pepe");
		for (Iterator iterator = TutorialUtils.getEntries().iterator(); iterator.hasNext();) {
			Tutorial tutorial = (Tutorial) iterator.next();
			System.out.println(tutorial);
		}
	}

}
